<!doctype html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"
      layout:decorator="base"
      th:with="pageTitle='编辑文件'">
<head>
    <link rel="stylesheet" th:href="@{/css/index.css}">
    <script th:src="@{/js/wangEditor.min.js}"></script>
    <style>
        .w-e-text-container {
            height: 440px !important;
        }

    </style>
</head>
<body>
<th:block layout:fragment="custom_content">
    <el-form ref="form" :model="form" enctype="multipart/form-data">
        <!--<el-button type="primary" size="mini" @click="updateRule">保存</el-button>-->
        <!--<el-button type="primary" size="mini" @click="goback">返回详情页</el-button>-->

        <el-form-item label="文件">
            <input id="excelFile" type="file" name="excelFile" style="display:none"
                   onchange="excelFileChange(this.files)"/>
            <el-button type="primary" @click="selectExcelFile" size="mini">选择文件</el-button>
            <span id="excelFileName">{{excelFileName}}</span>
            <el-button type="primary" @click="submitUpload" size="mini">文件上传<i
                    class="el-icon-upload el-icon--right"></i></el-button>

        </el-form-item>

        <input type="hidden" id="id"/>
        <!--标题：-->
        <el-form-item label="标题">
            <el-input v-model="form.title" id="title" maxlength="120"></el-input>
        </el-form-item>

        <div id="editor" style="background-color:#fff; position:relative;z-index:1;height:470px;max-height: 600px;margin-top:5px;width:98%">
        </div>
        <br>
        <!--&lt;!&ndash; 上传附件 &ndash;&gt;-->
        <!--<el-form-item label="上传附件：">-->
            <!--<input id="excelFileExtra" type="file" name="excelFileExtra" style="display:none"-->
                   <!--onchange="excelFileExtraChange(this.files)"/>-->
            <!--<el-button size="mini" type="primary" @click="selectExcelFileExtra" class="loginBtn">选择附件</el-button>-->
        <!--</el-form-item>-->

        <!--&lt;!&ndash;附件列表&ndash;&gt;-->
        <!--<el-table :data="extraFiles" style="width: 70%">-->
            <!--<el-table-column prop="fileName" label="文件名" width="200"></el-table-column>-->
            <!--<el-table-column prop="fileUrl" label="链接地址" width="350"></el-table-column>-->
            <!--<el-table-column label="操作" width="80">-->
                <!--<template slot-scope="scope">-->
                    <!--<el-button size="mini" type="danger" @click="delFile(scope.$index, scope.row.fileId)">删除</el-button>-->
                <!--</template>-->
            <!--</el-table-column>-->
        <!--</el-table>-->

        <el-button type="primary" size="mini" @click="updateRule">保存</el-button>
        <el-button type="primary" size="mini" @click="goback">返回详情页</el-button>


    </el-form>

</th:block>
<th:block layout:fragment="javascript">
    <script>
        var indexVue = new Vue({
            el: '#app',
            data: function () {
                return {
                    siderWidthDialog:false,
                    siderbarWidth:15,
                    form: {
                        title: '',
                        content: ''
                    },
                    breadcrumbs:['编辑文件'],
                    isCollapse: false,
                    defaultIndex: '1',
                    excelFileName: '',
                    menus: [],
                    regulationMenus: [],
                    extraFiles: [],
                    deptTrees:[]
                }
            },
            methods: {

                submitUpload: function () {
                    var $this = this;
                    var formData = new FormData();
                    if ($('#excelFile')[0].files[0] == undefined) {
                        $this.$message('请选择文件上传');
                    }
                    formData.append('excelFile', $('#excelFile')[0].files[0]);
                    formData.append('title', "");

                    var loading = this.$loading({
                        lock: true,
                        text: '上传中...',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });

                    $.ajax({
                        url: '/regulation/savesingleNew',
                        type: 'POST',
                        cache: false,
                        data: formData,
                        processData: false,
                        contentType: false
                    }).done(function (data) {
                        loading.close();
                        if (data.status == 1) {
                            var b = new Base64();
                            var text = b.decode(data.value.content);
                            editor.txt.html(text);
                            // setValue(data.value.content);
                            $("#editor p[style*='text-align:right']").css('text-align', 'justify');
                            $("#editor p[style*='text-align: right']").css('text-align', 'justify');
                        } else {
                            $this.$message.error(data.msg);
                        }
                    }).fail(function (res) {
                        loading.close();
                        $this.$message({
                            showClose: true,
                            message: '上传失败',
                            type: 'error'
                        });
                    });
                },
                selectExcelFile: function () {
                    $('#excelFile').click();
                },
                updateRule: function () {
                    var $this = this;
                    var data = new Object();

                    if ($('#title').val() == '') {
                        $this.$message({
                            showClose: true,
                            message: '请输入标题',
                            type: 'error'
                        });
                        return;
                    }
                    if (editor.txt.html() == '<p><br></p>') {
                        $this.$message({
                            showClose: true,
                            message: '请输入文件内容',
                            type: 'error'
                        });
                        return;
                    }

                    var loading = this.$loading({
                        lock: true,
                        text: '上传中...',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });

                    data.id = $("#id").val();
                    data.title = $('#title').val();
                    // data.content = CKEDITOR.instances.TextArea1.getData();
                    data.content = getValue();
                    $.ajax({
                        cache: true,
                        url: '/regulation/updaterule?newDate='+Math.random(),
                        type: 'POST',
                        data: JSON.stringify(data, "\t"),
                        dataType: 'json',
                        contentType: 'application/json',
                        async: false,
                        success: function (data) {

                            loading.close();

                            if (data.status == 1) {
                                $this.$message('保存成功');
                            } else {
                                $this.$message.error(data.msg);
                            }

                            // location.href = window.location.host+"/regulation/createmenu";
                        }
                    });
                    changeFooterHeight();

                },
                addHeight: function () {
                    var $this = this;
                    $this.$nextTick(function () {
                        changeFooterHeight();
                    })
                },
                delFile: function (index, fileId) {
                    this.extraFiles.splice(index, 1);
                    changeFooterHeight();
                },
                selectExcelFileExtra: function () {
                    $('#excelFileExtra').click();
                },
                goback: function () {
                    var id =   $("#id").val();
                    location.href = "/regulation/showregulation/"+id;
                },
                initMenu: function () {
                    var $this = this;
                    var data = commonInitMenu($this);
                },
                toggleMenu: function () {
                    this.isCollapse = !this.isCollapse;
                    window.localStorage.setItem('isCollapse',this.isCollapse);
                },
                changeSiderWidth:function(value){
                    changeSiderWidth(this,value);
                },
                openChangeSiderWidth:function(){
                    this.siderWidthDialog=true;
                }
            },
            created: function () {
                initCssProperty(this);
            }
        });
        var E = window.wangEditor;
        var editor = new E('#editor');

        $(function () {
            indexVue.initMenu();
            // var id = sessionStorage.getItem("id");
            var strs = location.href.split("/");
            var id = strs[strs.length - 1];
            $("#id").val(id);
            // $("#input").cleditor();
            // var E = window.wangEditor;
            // var editor = new E('#editor');
            editor.customConfig.uploadImgShowBase64 = true;  // 使用 base64 保存图片

            editor.create();
// //如果是在ASP.NET环境下用的服务器端控件<TextBox>
//             CKEDITOR.replace('tbContent');

// //如果<TextBox>控件在母版页中，要这样写
//             CKEDITOR.replace('<%=tbContent.ClientID.Replace("_","$") %>');
            $.ajax({
                cache: true,
                url: '/regulation/showrule?newDate='+Math.random(),
                type: 'GET',
                data: {ruleId: id},
                dataType: 'json',
                contentType: 'application/json',
                async: false,
                success: function (data) {
                    var b = new Base64();
                    indexVue.form.title = data.value.rule.title;
                    var text = b.decode(data.value.rule.content);

                    editor.txt.html(text);
                    $("#editor p[style*='text-align:right']").css('text-align','justify');
                    $("#editor p[style*='text-align: right']").css('text-align','justify');
                    indexVue.addHeight();
                    // indexVue.form.content = data.value.rule.content;
                    // indexVue.form.content = HTMLDecode(data.value.rule.content);
                    // $("#TextArea1").val(data.value.rule.content);
                }
            });
            changeFooterHeight();
        })

        function excelFileExtraChange(files) {
            var $this = this;
            var formData = new FormData();
            if($('#excelFileExtra')[0].files[0]==undefined){
                return;
            }
            formData.append('excelFileExtra', $('#excelFileExtra')[0].files[0]);
            $.ajax({
                url: '/regulation/savefile',
                type: 'POST',
                cache: false,
                data: formData,
                processData: false,
                contentType: false
            }).done(function (res) {
                var item = {
                    fileId: res.value.fileId,
                    fileName: res.value.fileName,
                    fileUrl: res.value.fileUrl
                };

                indexVue.extraFiles.unshift(item);

            }).fail(function (res) {
                indexVue.$alert('上传附件失败！', '提示', {
                    confirmButtonText: '确定',
                    callback: function callback() {
                    }
                });

            });

        }


        function getContent() {
            return editor.txt.html();
        }

        //解析转义后的富文本标签
        function HTMLDecode(text) {
            var temp = document.createElement("div");
            temp.innerHTML = text;
            var output = temp.innerText || temp.textContent;
            temp = null;
            return output;
        }

        function getValue() {
            var b = new Base64();
            return b.encode(editor.txt.html());
        }

        function getCaption(obj) {
            var index = obj.lastIndexOf("\.");
            obj = obj.substring(index + 1, obj.length);
            return obj;
        }

        function excelFileChange(files) {
            if (files) {
                var Doc = getCaption(files[0].name);

                if (Doc === 'doc' || Doc === 'docx') {
                    indexVue.excelFileName = files[0].name;
                    $("#excelFileName").val(files[0].name);
                    // this.$refs.input1.value = files[0].name;
                    return false;
                } else {
                    indexVue.$alert('上传文件只能是 doc/docx 格式!请重新选择！', '提示', {
                        confirmButtonText: '确定',
                        callback: function callback() {
                        }
                    });

                    return false;
                }
            }
        }

        function Base64() {

            // private property
            _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

            // public method for encoding
            this.encode = function (input) {
                var output = "";
                var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
                var i = 0;
                input = _utf8_encode(input);
                while (i < input.length) {
                    chr1 = input.charCodeAt(i++);
                    chr2 = input.charCodeAt(i++);
                    chr3 = input.charCodeAt(i++);
                    enc1 = chr1 >> 2;
                    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                    enc4 = chr3 & 63;
                    if (isNaN(chr2)) {
                        enc3 = enc4 = 64;
                    } else if (isNaN(chr3)) {
                        enc4 = 64;
                    }
                    output = output +
                        _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                        _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
                }
                return output;
            }

            // public method for decoding
            this.decode = function (input) {
                var output = "";
                var chr1, chr2, chr3;
                var enc1, enc2, enc3, enc4;
                var i = 0;
                input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
                while (i < input.length) {
                    enc1 = _keyStr.indexOf(input.charAt(i++));
                    enc2 = _keyStr.indexOf(input.charAt(i++));
                    enc3 = _keyStr.indexOf(input.charAt(i++));
                    enc4 = _keyStr.indexOf(input.charAt(i++));
                    chr1 = (enc1 << 2) | (enc2 >> 4);
                    chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                    chr3 = ((enc3 & 3) << 6) | enc4;
                    output = output + String.fromCharCode(chr1);
                    if (enc3 != 64) {
                        output = output + String.fromCharCode(chr2);
                    }
                    if (enc4 != 64) {
                        output = output + String.fromCharCode(chr3);
                    }
                }
                output = _utf8_decode(output);
                return output;
            }

            // private method for UTF-8 encoding
            _utf8_encode = function (string) {
                string = string.replace(/\r\n/g, "\n");
                var utftext = "";
                for (var n = 0; n < string.length; n++) {
                    var c = string.charCodeAt(n);
                    if (c < 128) {
                        utftext += String.fromCharCode(c);
                    } else if ((c > 127) && (c < 2048)) {
                        utftext += String.fromCharCode((c >> 6) | 192);
                        utftext += String.fromCharCode((c & 63) | 128);
                    } else {
                        utftext += String.fromCharCode((c >> 12) | 224);
                        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                        utftext += String.fromCharCode((c & 63) | 128);
                    }

                }
                return utftext;
            }

            // private method for UTF-8 decoding
            _utf8_decode = function (utftext) {
                var string = "";
                var i = 0;
                var c = c1 = c2 = 0;
                while (i < utftext.length) {
                    c = utftext.charCodeAt(i);
                    if (c < 128) {
                        string += String.fromCharCode(c);
                        i++;
                    } else if ((c > 191) && (c < 224)) {
                        c2 = utftext.charCodeAt(i + 1);
                        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                        i += 2;
                    } else {
                        c2 = utftext.charCodeAt(i + 1);
                        c3 = utftext.charCodeAt(i + 2);
                        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                        i += 3;
                    }
                }
                return string;
            }
        }

    </script>
</th:block>
</body>
</html>